<template>
	<div class="login-status-container" v-if="showStatus">
		<!-- 未实名认证/未绑定企业（50001） -->
		<!-- 注意：只有50001状态有关闭按钮，用户可以选择暂时不绑定，先浏览法律法规等公开内容 -->
		<div v-if="statusCode === '50001'" class="status-card">
			<!-- 关闭按钮 - 允许用户暂时关闭，先访问公开内容 -->
			<!-- <div class="close-icon" @click="closeDialog">
				<van-icon name="cross" size="20" color="#999" />
			</div> -->
			<div class="status-content">
				<h3>您尚未绑定企业，如是企业用户请先完成企业绑定！</h3>
				<div class="status-actions">
					<button @click="closeDialog" class="btn-primary">确定</button>
				</div>
			</div>
		</div>

		<!-- 待审核 -->
		<div v-if="statusCode === '50002'" class="status-card">
			<div class="status-content">
				<p>您的绑定企业申请尚未审核完毕，请稍等！</p>
				<div class="status-actions">
					<button @click="refresh" class="btn-primary">刷新</button>
				</div>
			</div>
		</div>

		<!-- 审核未通过 -->
		<div v-if="statusCode === '50003'" class="status-card">
			<!-- 关闭按钮 - 允许用户暂时关闭，先访问公开内容 -->
			<div class="close-icon" @click="closeDialog">
				<van-icon name="cross" size="20" color="#999" />
			</div>
			<div class="status-content">
				<p class="text-desc">{{ statusMessage }}</p>
				<div class="status-actions">
					<button @click="goToBind" class="btn-primary">重新绑定</button>
				</div>
			</div>
		</div>
	</div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { showLoadingToast, showSuccessToast, showFailToast, closeToast } from 'vant'

const router = useRouter()
const userStore = useUserStore()

const props = defineProps({
	statusCode: {
		type: String,
		default: '',
	},
	statusMessage: {
		type: String,
		default: '',
	},
	show: {
		type: Boolean,
		default: false,
	},
})

const showStatus = ref(props.show)

// 监听显示状态（立即执行）
watch(
	() => props.show,
	(newVal) => {
		console.log('LoginStatus: show prop changed:', newVal)
		showStatus.value = newVal
	},
	{ immediate: true }
)

// 监听状态码变化（立即执行）
watch(
	() => props.statusCode,
	(newCode) => {
		console.log('LoginStatus: statusCode changed:', newCode)
		if (newCode && ['50001', '50002', '50003'].includes(newCode)) {
			showStatus.value = true
		}
	},
	{ immediate: true }
)

const emit = defineEmits(['close', 'refresh'])

// 关闭弹窗
const closeDialog = () => {
	showStatus.value = false
	emit('close')
}

// 去绑定页面
const goToBind = () => {
	// 先关闭弹窗，再跳转
	emit('close')
	// 延迟跳转，确保弹窗关闭动画完成
	setTimeout(() => {
		router.push('/company/bound')
	}, 100)
}

// 刷新登录状态 - 优先使用缓存 code，避免不必要的重新授权
const refresh = async () => {
	try {
		// 检查 code 是否有效
		showStatus.value = false
		if (userStore.isCodeValid) {
			showLoadingToast({
				message: '正在刷新...',
				forbidClick: true,
			})

			// 使用缓存的 code 重新登录
			const result = await userStore.loginWithCode(userStore.code)

			closeToast()

			if (result.success) {
				// 登录成功，关闭弹窗并通知父组件刷新数据
				console.log('✅ 刷新登录状态成功，用户已通过认证')
				showSuccessToast('您已通过认证')

				// 先关闭弹窗
				showStatus.value = false
				emit('close')

				// 通知父组件刷新数据（重新加载菜单等）
				console.log('🔄 通知父组件刷新数据')
				emit('refresh')
			} else if (['50001', '50002', '50003'].includes(result.code)) {
				// 仍然是特殊状态，更新显示
				showFailToast('状态未变更')
				showStatus.value = true
			} else {
				showFailToast(result.error || '刷新失败')
			}
		} else {
			// code 已过期，需要重新授权
			showFailToast('登录已过期，即将跳转授权页面')
			setTimeout(() => {
				userStore.redirectToAuth()
			}, 1500)
		}
	} catch (error) {
		closeToast()
		console.error('刷新失败:', error)
		showFailToast('刷新失败')
	}
}
</script>

<style scoped>
.login-status-container {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 9999;
	padding: 20px;
}

.status-card {
	background: white;
	border-radius: 12px;
	padding: 30px;
	max-width: 400px;
	width: 100%;
	text-align: center;
	box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
	position: relative;
}

.close-icon {
	position: absolute;
	top: 8px;
	right: 8px;
	cursor: pointer;
	z-index: 1;
	display: flex;
	align-items: center;
	justify-content: center;
	width: 32px;
	height: 32px;
	border-radius: 50%;
	transition: background-color 0.3s;
}

.close-icon:hover {
	background-color: #f5f5f5;
}

.close-icon:active {
	background-color: #e8e8e8;
}

.status-icon {
	font-size: 48px;
	margin-bottom: 16px;
}

.status-content h3 {
	margin: 0 0 12px 0;
	font-size: 18px;
	font-weight: 600;
	color: #333;
}
.text-desc {
	text-align: left;
}

.status-content p {
	margin: 0 0 24px 0;
	color: #666;
	line-height: 1.5;
}

.status-actions {
	display: flex;
	justify-content: center;
	gap: 12px;
}

.btn-primary {
	background: #1976d2;
	color: white;
	border: none;
	border-radius: 6px;
	padding: 12px 24px;
	font-size: 16px;
	cursor: pointer;
	transition: background 0.3s;
}

.btn-primary:hover {
	background: #1565c0;
}

.text-muted {
	color: #999;
	font-size: 14px;
}
</style>
